const orderModel = require('../../db/order')
const respJson = require('../../utils/respJson')
const writeErr = require('../../utils/writeErr')
const cartModel = require('../../db/cart')

module.exports = {
    async create(req, resp) {
        let {
            eatWay,
            totalPrice,
            userId,
            cartIds,
            dishName
        } = req.body
        let orderNo = +new Date() + String(Math.floor(Math.random() * 1000))
        let bool = true

        try {
            while (bool) {
                let docs = await orderModel.findOne({
                    orderNo
                })
                if (docs) {
                    orderNo = +new Date() + String(Math.floor(Math.random() * 1000))
                } else {
                    bool = false
                }
            }
        } catch (err) {
            writeErr(err)
            respJson(resp, 511, '生成订单号失败！')
        }

        let payStatus = '已支付'
        let zeroDate = +new Date(new Date().setHours(0, 0, 0, 0))
        let lastDate = +new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)
        let code
        try {
            let docs = await orderModel.count({
                createdAt: {
                    $gte: zeroDate
                },
                createdAt: {
                    $lte: lastDate
                }
            })
            code = docs + 1
        } catch (err) {
            writeErr(err)
            respJson(resp, 512, '生成取餐码失败！')
        }

        //将数据存入数据库
        try {
            let docs = await orderModel.insertMany({
                orderNo,
                payStatus,
                code,
                eatWay,
                totalPrice,
                userId,
                dishName
            })
            try {
                await cartModel.deleteOne({
                    _id: cartIds
                })
                // respJson(resp, 200, '购物车删除成功！')
            } catch (err) {
                writeErr(err)
                respJson(resp, 514, '购物车删除失败！')
            }
            respJson(resp, 200, '订单生成成功！', docs)

        } catch (err) {
            writeErr(err)
            respJson(resp, 513, '订单生成失败！')
            return
        }
    },

    async getall(req, resp) {
        let {
            userId
        } = req.params
        try {
            let docs = await orderModel.find({
                userId
            })
            respJson(resp, 200, '获取订单数量成功！', {
                orders: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 515, '查询订单失败！')
        }
    }
}